package com.core.cloudgateway.exception;


import com.alibaba.fastjson.JSON;
import com.core.cloudcommon.CommonCustomException;
import com.core.cloudcommon.CommonInteger;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author =====Lqj=====
 * @className GatewayExceptionHandler
 * @description 网关自定义异常处理
 * @create 2024/11/18 20:47
 **/

@Order(-1)
@Component
public class GatewayExceptionHandler implements WebExceptionHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 设置返回的 HTTP 状态码
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        CommonCustomException customEx = (CommonCustomException) ex;
        // 构造返回的错误数据
        Map<String, Object> response = new HashMap<>(CommonInteger.Integer16);
        response.put("success", customEx.isSuccess());
        response.put("timestamp", customEx.getTimestamp());
        response.put("code", customEx.getCode());
        response.put("message", customEx.getMessage());
        response.put("requuid", customEx.getRequuid());

        // 设置响应状态码
        exchange.getResponse().setStatusCode(status);
        // 设置响应内容类型为 JSON
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 将错误信息写入响应体
        byte[] jsonBytes = JSON.toJSONBytes(response);

        return exchange.getResponse().writeWith(
                Mono.just(exchange.getResponse().bufferFactory().wrap(jsonBytes))
        );
    }
}
